2
2
.
.
9
9
.
.
4
4
L
L
o
o
c
c
a
a
t
t
i
i
o
o
n
n
-
-
C
C
o
o
n
n
s
s
t
t
r
r
u
u
c
c
t
t
o
o
r
r
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
[
[
R
R
]
]
This tutorial shows how to use @Autowired to inject instance into Constructor's Input Parameter.
When @Component Class is instantiated Constructor is called (just like when instantiating any other Java Class).
If Constructor accepts Spring Component, Spring Boot will automatically create an Instance of it.
@Autowired Annotation before the Constructor is optional, in other words
only Methods with @Autowired Annotation will get its Parameters injected
but Constructor Parameters get injected by default (even if Constructor is not Annotated with @Autowired)
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller and @RequestMapping. Includes Tomcat Server.
MyService
http://localhost:8080/Hello
Tomcat
Browser
MyController
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_autowired_constructor (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
Create Package: services (inside main package)
Create Class: MyService.java (inside package controllers)
MyController.java
package com.ivoronline.springboot_autowired_constructor.controllers;
import com.ivoronline.springboot_autowired_constructor.services.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class MyController {
MyService myService;
@Autowired
public MyController(MyService myService) {
this.myService = myService;
}
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
String Results = myService.sayHello();
return Results;
}
}
MyService.java
package com.ivoronline.springboot_autowired_constructor.services;
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String sayHello() {
return "Hello";
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>